package utils

import (
	"errors"
	"github.com/go-resty/resty/v2"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"
)

func GetExt(name string) string {
	tmpExt := strings.Split(name, ".")
	if len(tmpExt) == 0 {
		log.Fatalf("获取文件:%s扩展失败", name)
	}
	return strings.ToLower(tmpExt[len(tmpExt)-1])
}

// 发起get请求
func HttpGet(url string, params map[string]string, timeOut time.Duration) (string, error) {
	client := resty.New()
	client.SetTimeout(timeOut) //10秒超时
	resp, err := client.R().
		SetQueryParams(params).
		SetHeader("Accept", "application/json").
		Get(url)
	return resp.String(), err
}

// 发起post请求
func HttpPost(url string, params map[string]string, timeOut time.Duration) (string, error) {
	client := resty.New()
	client.SetTimeout(timeOut) //10秒超时
	resp, err := client.R().
		SetBody(params).
		SetHeader("Accept", "application/json").
		Post(url)
	return resp.String(), err
}

// 获取当前可执行文件所在目录
func GetCurrentPath() (string, error) {
	file, err := exec.LookPath(os.Args[0])
	if err != nil {
		return "", err
	}
	path, err := filepath.Abs(file)
	if err != nil {
		return "", err
	}
	i := strings.LastIndex(path, string(os.PathSeparator))
	if i < 0 {
		return "", errors.New(`error: Can't find "/" or "\"`)
	}
	return path[0 : i+1], nil
}

// 三目运算的函数
func Ternary(condition bool, trueVal, falseVal interface{}) interface{} {
	if condition {
		return trueVal
	}
	return falseVal
}
